package cn.com.cetccst.devicerestriction.timefence;

import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import cn.com.cetccst.datacenter.policy.fence.TimeFence;

//时间围栏P2,已具备初步功能后续完善
public class TimeFenceManager {
    private static final String TAG = "TimeFenceManager";

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm");

    public TimeFenceManager() {
        //目前没有把时间围栏单独放在一个表里，而是使用了每个管控项自己数据结构里得时间围栏。
    }

    public boolean isInTimeFence(List<TimeFence> fences) {
        if (fences == null || fences.isEmpty()) {
            return false;
        }
        return isInTimeFence(Calendar.getInstance(), fences);
    }

    public List<TimeFence> getTodayFences(int dayOfWeek, List<TimeFence> fences) {
        List<TimeFence> todayFences = new ArrayList<>();
        for (TimeFence fence : fences) {
            if (fence.getDayOfWeek() == dayOfWeek) {
                todayFences.add(fence);
            }
        }

        return todayFences;
    }

    private boolean isInTimeFence(Calendar now, List<TimeFence> fences) {

        List<TimeFence> todayFences = getTodayFences(now.get(Calendar.DAY_OF_WEEK), fences);
        for (TimeFence fence : todayFences) {
            try {

                int year = now.get(Calendar.YEAR);
                int month = now.get(Calendar.MONTH) + 1;
                int day = now.get(Calendar.DAY_OF_MONTH);
                Date start = SDF.parse(String.format(Locale.ENGLISH, "%d-%d-%d %s", year, month, day, fence.getStartTime()));
                Date end = SDF.parse(String.format(Locale.ENGLISH, "%d-%d-%d %s", year, month, day, fence.getEndTime()));
                String timeLog = "Time fence is from %s to %s, and current time is %s";
                Log.d(TAG,
                        String.format(timeLog, start, end, now.getTime()));

                if (start.before(now.getTime()) && end.after(now.getTime())) {
                    Log.i(TAG, "Now is in the time fence.");
                    return true;
                }
            } catch (Exception ex) {
                Log.e(TAG, "Parse fence start end time exception", ex);
            }
        }
        Log.i(TAG, "Now is out of time fence.");
        return false;
    }
}
